<?php
declare(strict_types=1);

namespace Dreamcat\ApolloPhp\Impl\Saver;

use Dreamcat\ApolloPhp\ConfigSaverInterface;
use Dreamcat\ApolloPhp\Popo\ConfigResult;

/**
 * 将每个名空间单独保存为独立文件
 * @author vijay
 */
class SingleSaver implements ConfigSaverInterface
{
    /** @var array 名空间和对应文件的映射表 */
    private $configMap = [];

    /**
     * ConfigSaver constructor.
     * @param array $configMap 名空间和对应文件的映射表
     */
    public function __construct(array $configMap)
    {
        $this->configMap = $configMap;
    }

    /**
     * @inheritDoc
     */
    public function saveConfig(ConfigResult $configResult): bool
    {
        if (!isset($this->configMap[$configResult->getNamespaceName()])) {
            return true;
        }

        # todo 允许设置解析策略
        $fileName = $this->configMap[$configResult->getNamespaceName()];
        $pulledConfigs = $configResult->getConfigurations();
        $configs = [];
        foreach ($pulledConfigs as $key => $config) {
            $keys = explode(".", $key);
            $cur = &$configs;
            for ($idx = 0; $idx < count($keys) - 1; ++$idx) {
                if (!isset($cur[$keys[$idx]])){
                    $cur[$keys[$idx]] = [];
                }
                $cur = &$cur[$keys[$idx]];
            }
            $cur[$keys[count($keys) - 1]] = $config;
        }

        # todo 允许设置保存策略
        return file_put_contents($fileName, "<?php\nreturn " . var_export($configs, true) . ";\n") !== false;
    }

    /**
     * @inheritDoc
     */
    public function onSaveAll(): void
    {
    }
}

# end of file
